package gui;

import dal.object.MapObject;
import dal.object.rocks.MarbleRock;
import gui.event.SwitchObject;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Vector;


@SuppressWarnings("serial")
public class RockDrawer extends JPanel {
	private int halfImageWidth;
	private int imageWidth;
	private int imageHeight75;
	private int imageHeight25;
	private Image img;
	private Graphics gr;
	private Point location;
	private Vector<MapObject> vmo;
	private Dimension dimension;
	
	public RockDrawer(Dimension dim/*MapStruct ms*/) {
		this.setOpaque(false);
		
		dimension = dim; // ms.getDimension();

		vmo = new Vector<MapObject>();
		
		for(int i = 0; i < dimension.width * dimension.height; ++i){
			if((int) (Math.random() * 5) == 0) {
				vmo.add(new MarbleRock());
			} else {
				vmo.add(null);
			}
		}

		this.addMouseListener(new SwitchObject(vmo));
		
		imageWidth = 38; //img.getWidth();
		halfImageWidth = 19; //imageWidth/2;
		imageHeight75 = 33; //(int) (img.getHeight() * 0.75);
		imageHeight25 = 11; //(int) (img.getHeight() * 0.25);
		
		// Setting panel size
		this.setSize(new Dimension(dimension.width * imageWidth + ((dimension.height > 1) ? halfImageWidth : 0), dimension.height * imageHeight75 + imageHeight25));
	}
	
	// Drawing grounds
	protected void paintComponent(Graphics g) {
		if (img == null) {
			img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TRANSLUCENT);
			gr = img.getGraphics();
		}
		
		location = new Point(0,0);
		
		// Setting MapObjects' location and drawing them
		for (int i = 0; i < dimension.getHeight(); i++) {
			if (i%2 == 0)
				location.x = 0;
			else
				location.x = halfImageWidth;
			
			for (int j = 0; j < dimension.getWidth(); j++) {
				MapObject mo = vmo.get((int) (i * dimension.getWidth() + j));
				if (mo != null) {
					mo.setLocation(location);
					mo.drawObject(gr);
				}
				location.x += imageWidth;
			}
			location.y += imageHeight75;
		}
		
		g.drawImage(img, 0, 0, null);
	}
}